package edu.service.impl;

import edu.service.UserRoleService;
import edu.vo.UserRole;
import edu.vo.ID.UserRoleId;
import edu.repository.UserRoleRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserRoleServiceImpl implements UserRoleService {

    private final UserRoleRepository userRoleRepository;

    public UserRoleServiceImpl(UserRoleRepository userRoleRepository) {
        this.userRoleRepository = userRoleRepository;
    }

    @Override
    public UserRole saveUserRole(UserRole userRole) {
        return userRoleRepository.save(userRole);
    }

    @Override
    public Optional<UserRole> getUserRoleById(UserRoleId id) {
        return userRoleRepository.findById(id);
    }

    @Override
    public List<UserRole> getAllUserRoles() {
        return userRoleRepository.findAll();
    }

    @Override
    public void deleteUserRoleById(UserRoleId id) {
        userRoleRepository.deleteById(id);
    }

    @Override
    public UserRole updateUserRole(UserRoleId id, UserRole userRole) {
        return userRoleRepository.findById(id)
                .map(existingUserRole -> {
                    existingUserRole.setUser(userRole.getUser());
                    existingUserRole.setRole(userRole.getRole());
                    return userRoleRepository.save(existingUserRole);
                })
                .orElse(null);
    }

    @Override
    public void deleteByUserId(Integer userId) {
        userRoleRepository.deleteByUserId(userId);
    }
}